package com.yzg.sign.project.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
@Slf4j
public class UploadUtil
{


    private static String  path ;

    @Value("${upload.windows.filePath}")
    public void setPath(String path) {
        this.path = path;
    }

    public static String upload(MultipartFile file, String path, String fileName) throws Exception {
    // 生成新的文件名
    String realPath = path + "/" + UUID.randomUUID().toString().replace("-", "")+fileName.substring(fileName.lastIndexOf("."));
    File dest = new File(realPath);
    // 判断文件父目录是否存在
    dest.getParentFile().mkdir();
    // 保存文件
    file.transferTo(dest);
    return dest.getName();
    }

    public static void deleteDir(String dirPath){
    File file = new File(path+dirPath);// 读取
    if(file.isFile())
    { // 判断是否是文件夹
    file.delete();// 删除
    } else{
        File[] files = file.listFiles(); // 获取文件
        if(files == null){
        file.delete();// 删除
      }else{
         for (int i = 0; i < files.length; i++){// 循环
        deleteDir(files[i].getAbsolutePath());
         }
         file.delete();// 删除
        }
      }
    }


    public static List<String> save(List<MultipartFile> files)
    {
        List<String> images=new ArrayList<>();
        for(MultipartFile file:files) {
            //获取绝对路径
            String realPath = path;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            //文件存放的目录
            File folder = new File(realPath + format);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String oldName = file.getOriginalFilename();
            //文件后缀
            String suffix = oldName.substring(oldName.lastIndexOf("."));
            //文件新名字
            String newName = UUID.randomUUID().toString() + suffix;
            try {
                File targetFile = new File(folder, newName);

                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                } else {
                    targetFile.delete();
                }
                file.transferTo(targetFile);
                String filePath ="/uploadFile/" + format +"/"+ newName;
                images.add(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return images;
    }


    public static void buildExcelDocument(HttpServletResponse response,String filePath,String type,String fileName)
    {

        if (filePath.contains("%")) {
            try {
                filePath = URLDecoder.decode(filePath, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                log.debug("responseFileStream decode error:" + e.toString());
            }
        }
       // filePath = path+filePath.substring(filePath.indexOf("uploadFile")+11).replace("/","\\");
        filePath = path+filePath.substring(filePath.indexOf("uploadFile")+11);
        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(filePath));
            String fileType = type.toLowerCase();
            //设置文件ContentType类型
            if ("jpg,jepg,gif,png".contains(fileType)) {//图片类型
                response.setContentType("image/" + fileType);
            } else if ("pdf".contains(fileType)) {//pdf类型
                response.setContentType("application/pdf");
            } else {//自动判断下载文件类型
                response.setContentType("multipart/form-data");
            }
            //设置文件头：最后一个参数是设置下载文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (FileNotFoundException e) {
            log.error("responseFileStream error:FileNotFoundException" + e.toString());
        } catch (Exception e) {
            log.error("responseFileStream error:" + e.toString());
        } finally {
            try {
                out.close();
                in.close();
            } catch (NullPointerException e) {
                log.error("responseFileStream stream close() error:NullPointerException" + e.toString());
            } catch (Exception e) {
                log.error("responseFileStream stream close() error:" + e.toString());
            }
        }

    }


}
